"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : autocommit
Case Name   : 关闭自动提交，执行DML语句(insert/update/drop)，回滚/提交，会话2查询是否回滚/提交
Create At   : 2023/01/17
@zou_jialiang0501162244
Description :
    1、兼容B库建表
    2、开启会话1连接B库，关闭自动提交，表中插入两条数据，会话2查询，提交，
       再插入两条数据，回滚前后查询
    3、会话2统计表数据，会话1提交后再次查询
    4、关闭自动提交，修改表数据，回滚/提交
    5、新开会话查询表数据
    6、关闭自动提交，删除表数据，回滚/提交
    7、查询表数据
    8、清理环境
Expect      :
    1、成功
    2、执行成功，回滚前查询出4条数据，回滚后2条数据
    3、无数据，会话1提交后查询到2条数据
    4、执行成功
    5、2条数据
    6、成功
    7、1条数据
    8、成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class TestAutocommit(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_autocommit_0033'
        self.index_name = 'i_autocommit_0033'
        self.db_name = 'db_autocommit_0033'
        self.log.info("-----预置兼容B库-----")
        preset_db = f"drop database if exists {self.db_name};" \
                    f"create database {self.db_name} dbcompatibility 'B';"
        preset_db_res = self.pri_sh.execut_db_sql(preset_db)
        self.log.info(preset_db_res)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, preset_db_res,
                      f"创建兼容B库失败")

    def test_autocommit(self):
        text1 = '-----step1:兼容B库建表并插入数据;expect:成功-----'
        self.log.info(text1)
        preset_tb = f"drop table if exists {self.tb_name};" \
                    f"create table {self.tb_name}(c_id int, c_real real, " \
                    f"c_char char(20) default null, c_clob clob, " \
                    f"c_raw raw(20), c_blob blob, c_date date);"
        preset_res = self.pri_sh.execut_db_sql(preset_tb, dbname=self.db_name)
        self.log.info(preset_tb)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, preset_res,
                      f"建表失败: {text1}")

        text2 = '-----step2:开启会话1连接B库，关闭自动提交，表中插入两条' \
                '数据，会话2查询，提交，再插入两条数据，回滚前后查询;' \
                'expect:执行成功，回滚前查询出4条数据，回滚后2条数据-----'
        self.log.info(text2)
        sql1 = f"set autocommit to off;" \
               f"insert into {self.tb_name} values(1, 1.0002, 'aaaaa', " \
               f"'jjjsdfghjhi', '010111100', '010101101', " \
               f"date_trunc('hour', timestamp  '2001-02-16 20:38:40'));" \
               f"insert into t_autocommit_0033 values(2, 20.002, " \
               f"'bbbbb', 'jjjsdfghjhjui', '010111100', '010101101', " \
               f"date_trunc('hour', timestamp  '2001-02-16 20:38:40'));" \
               f"select pg_sleep(3); commit;" \
               f"insert into {self.tb_name} select * from {self.tb_name};" \
               f"select count(*) from {self.tb_name};" \
               f"rollback;" \
               f"select count(*) from {self.tb_name};"
        session1 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql1, '', self.db_name))
        session1.setDaemon(True)

        text3 = '-----step3:会话2统计表数据，会话1提交后再次查询;' \
                'expect:无数据，会话1提交后查询到2条数据-----'
        self.log.info(text3)
        sql2 = f"select count(*) from {self.tb_name};" \
               f"select pg_sleep(3);" \
               f"select count(*) from {self.tb_name};"
        session2 = ComThread(self.pri_sh.execut_db_sql,
                             args=(sql2, '', self.db_name))
        session2.setDaemon(True)
        # 先后启动线程，间隔1s
        session1.start()
        time.sleep(1)
        session2.start()
        session1.join(10)
        session2.join(10)
        result1 = session1.get_result()
        self.log.info(f'session1_results:\n {result1}')
        result2 = session2.get_result()
        self.log.info(f'session2_results:\n {result2}')
        self.assertIn('SET', result1, f"关闭自动提交失败: {text2}")
        self.assertEqual(result1.count(self.constant.INSERT_SUCCESS_MSG), 3,
                         f"insert失败: {text2}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, result1,
                      f"提交失败: {text2}")
        self.assertIn(self.constant.ROLLBACK_MSG, result1, f"回滚失败: {text2}")
        self.assertIn('4', result1, f"执行失败: {text2}")
        self.assertIn('2', result1.splitlines()[-2], f"执行失败: {text2}")
        self.assertEqual(result2.splitlines()[2].strip(), '0',
                         f"执行失败: {text3}")
        self.assertIn('2', result2.splitlines()[-2], f"执行失败: {text3}")

        text4 = '-----step4:关闭自动提交，修改表数据，回滚/提交;expect:成功-----'
        self.log.info(text4)
        sql = f"set autocommit=0;" \
              f"update {self.tb_name} set c_id = c_id + 2 where c_id = 1;" \
              f"rollback;" \
              f"select * from {self.tb_name};" \
              f"update {self.tb_name} t1 set (c_id, c_char) = (" \
              f"select c_id c1, c_char c2 from {self.tb_name} t2 " \
              f"where t1.c_id = t2.c_id + 1);" \
              f"select c_id, c_char from {self.tb_name};" \
              f"end;"
        sql_res = self.pri_sh.execut_db_sql(sql, dbname=self.db_name)
        self.log.info(sql_res)
        self.assertIn('SET', sql_res, f"关闭自动提交失败: {text4}")
        self.assertEqual(sql_res.count(self.constant.UPDATE_SUCCESS_MSG), 2,
                         f"update失败: {text4}")
        self.assertIn(self.constant.ROLLBACK_MSG, sql_res, f"回滚失败: {text4}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, sql_res,
                      f"执行失败: {text4}")
        self.assertTrue('1 | 1.0002 | aaaaa' in sql_res and
                        '2 | 20.002 | bbbbb' in sql_res, f"执行失败{text4}")
        self.assertTrue('   |   ' in sql_res and '1 | aaaaa' in sql_res,
                        f"执行失败{text4}")

        text5 = '-----step5:新开会话查询表数据;expect:2条数据-----'
        self.log.info(text5)
        select_res = self.pri_sh.execut_db_sql(
            f"select c_id, c_char from {self.tb_name};", dbname=self.db_name)
        self.log.info(select_res)
        self.assertIn('1 | aaaa', select_res, f"执行失败: {text5}")
        self.assertIn('2 rows', select_res, f"执行失败: {text5}")

        text6 = '-----step6:关闭自动提交，删除表数据，回滚/提交;expect:成功-----'
        self.log.info(text6)
        del_sql = f"set autocommit=0;" \
                  f"delete from {self.tb_name} where c_id is null;" \
                  f"end; select * from {self.tb_name};" \
                  f"delete from {self.tb_name} where c_id in (" \
                  f"select c_id from {self.tb_name} where c_real > 2.0);" \
                  f"select * from {self.tb_name}; rollback;"
        del_res = self.pri_sh.execut_db_sql(del_sql, dbname=self.db_name)
        self.log.info(del_res)
        self.assertIn('SET', del_res, f"关闭自动提交失败: {text6}")
        self.assertEqual(del_res.count(self.constant.DELETE_SUCCESS_MSG), 2,
                         f"delete失败: {text6}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, del_res,
                      f"执行失败: {text6}")
        self.assertIn(self.constant.ROLLBACK_MSG, del_res, f"回滚失败: {text6}")
        self.assertIn('1 | 20.002 | aaaaa', del_res, f"执行失败: {text6}")
        self.assertIn('0 rows', del_res.splitlines()[-3], f"执行失败: {text6}")

        text7 = '-----step7:新开会话查询表数据;expect:1条数据-----'
        self.log.info(text7)
        select_res = self.pri_sh.execut_db_sql(
            f"select count(*) from {self.tb_name}", dbname=self.db_name)
        self.log.info(select_res)
        self.assertEqual(select_res.splitlines()[2].strip(), '1',
                         f"执行失败: {text7}")

    def tearDown(self):
        text8 = '-----step8:清理环境 expect:成功-----'
        self.log.info(text8)
        drop_db_res = self.pri_sh.execut_db_sql(
            f"drop database if exists {self.db_name};")
        self.log.info(drop_db_res)
        self.assertIn(self.constant.DROP_DATABASE_SUCCESS, drop_db_res,
                      f"执行失败: {text8}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
